All files / src/app/api/products/[id] route.ts

94.02% Statements 189/201
67.64% Branches 23/34
100% Functions 3/3
94.02% Lines 189/201

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 2021x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 4x 1x 1x 2x 2x 2x 2x 2x 2x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 4x 1x 1x 2x 2x 2x 1x 1x 1x 1x 6x 6x 6x     6x 6x 6x 6x 6x     6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 2x 2x 2x     2x 2x 2x 2x 2x     2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
export const dynamic = "force-dynamic";
 
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from "@/lib/prisma";
import { Prisma } from "@prisma/client";
import { parseProductDetails } from "@/types/product";
import { measureApiPerformance } from "@/lib/performance";
import { getOrSet, CACHE_KEYS, CACHE_TTL, invalidatePattern } from "@/lib/core";
import {
  withErrorHandling,
  withAdmin,
  successResponse,
  ApiError,
  ApiSuccessResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
import { } from "next-auth";
 
// Type for product detail response
interface ProductDetailResponse {
  id: number;
  title: string;
  description: string | null;
  price: number;
  discountedPrice: number;
  stock: number;
  sku: string | null;
  category: { id: number; title: string; slug: string };
  specifications: unknown;
  details: string[];
  reviews: number;
  averageRating: number;
  reviewsList: unknown[];
  imgs: { thumbnails: string[]; previews: string[] };
  createdAt: Date;
  updatedAt: Date;
}
 
// GET /api/products/[id] - Get single product with details
async function handleGet(
  request: NextRequest,
  context?: RouteContext
): Promise<NextResponse<ApiSuccessResponse<ProductDetailResponse>>> {
  const startTime = Date.now();
 
  if (!context?.params) {
    throw ApiError.invalidId("product");
  }
 
  const resolvedParams = await context.params;
  const id = resolvedParams.id;
  const productId = parseInt(id);
 
  if (isNaN(productId)) {
    throw ApiError.invalidId("product");
  }
 
  // Use cache for product detail
  const transformedProduct = await getOrSet<ProductDetailResponse | null>(
    CACHE_KEYS.product(productId),
    async () => {
      const product = await prisma.product.findUnique({
        where: { id: productId },
        include: {
          category: true,
          images: {
            orderBy: { order: "asc" } },
          reviews: {
            include: {
              user: {
                select: {
                  id: true,
                  name: true,
                  email: true } } },
            orderBy: {
              createdAt: "desc" } } } });
 
      if (!product) {
        return null;
      }
 
      // Calculate average rating
      const totalRating = product.reviews.reduce(
        (sum: number, review: { rating: number }) => sum + review.rating,
        0
      );
      const averageRating =
        product.reviews.length > 0 ? totalRating / product.reviews.length : 0;
 
      // Transform to match frontend Product type
      return {
        id: product.id,
        title: product.title,
        description: product.description,
        price: product.price,
        discountedPrice: product.discountedPrice,
        stock: product.stock,
        sku: product.sku,
        category: product.category,
        specifications: product.specifications,
        details: parseProductDetails(product.details),
        reviews: product.reviews.length,
        averageRating,
        reviewsList: product.reviews,
        imgs: {
          thumbnails: product.images.map((img: { thumbnailUrl: string; url: string }) => img.thumbnailUrl || img.url),
          previews: product.images.map((img: { url: string }) => img.url) },
        createdAt: product.createdAt,
        updatedAt: product.updatedAt };
    },
    CACHE_TTL.productDetail
  );
 
  measureApiPerformance(`GET /api/products/${id}`, startTime);
 
  if (!transformedProduct) {
    throw ApiError.notFound("Product", id);
  }
 
  return successResponse(transformedProduct);
}
 
export const GET = withErrorHandling(handleGet);
 
// PATCH /api/products/[id] - Update product (Admin only)
async function handlePatch(request: NextRequest,
  context: RouteContext | undefined): Promise<NextResponse> {
  if (!context?.params) {
    throw ApiError.invalidId("product");
  }
 
  const { id } = await context.params;
  const productId = parseInt(id);
 
  if (isNaN(productId)) {
    throw ApiError.invalidId("product");
  }
 
  const body = await request.json();
 
  const {
    title,
    description,
    price,
    discountedPrice,
    stock,
    sku,
    categoryId } = body;
 
  const updateData: Prisma.ProductUpdateInput = {};
  if (title !== undefined) updateData.title = title;
  if (description !== undefined) updateData.description = description;
  if (price !== undefined) updateData.price = parseFloat(price);
  if (discountedPrice !== undefined)
    updateData.discountedPrice = parseFloat(discountedPrice);
  if (stock !== undefined) updateData.stock = parseInt(stock);
  if (sku !== undefined) updateData.sku = sku;
  if (categoryId !== undefined) updateData.category = { connect: { id: parseInt(categoryId) } };
 
  const product = await prisma.product.update({
    where: { id: productId },
    data: updateData,
    include: {
      category: true,
      images: true } });
 
  // Invalidate caches
  await invalidatePattern(`products:${productId}`);
  await invalidatePattern("products:list:*");
  await invalidatePattern("categories:*");
 
  return successResponse(product);
}
 
export const PATCH = withErrorHandling(withAdmin(handlePatch));
 
// DELETE /api/products/[id] - Delete product (Admin only)
async function handleDelete(_request: NextRequest,
  context: RouteContext | undefined): Promise<NextResponse> {
  if (!context?.params) {
    throw ApiError.invalidId("product");
  }
 
  const { id } = await context.params;
  const productId = parseInt(id);
 
  if (isNaN(productId)) {
    throw ApiError.invalidId("product");
  }
 
  await prisma.product.delete({
    where: { id: productId } });
 
  // Invalidate caches
  await invalidatePattern(`products:${productId}`);
  await invalidatePattern("products:*");
  await invalidatePattern("categories:*");
 
  return successResponse({ message: "Product deleted successfully" });
}
 
export const DELETE = withErrorHandling(withAdmin(handleDelete));